package show.me.the.money.service.core;

import java.lang.reflect.Method;
import java.util.HashMap;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import show.me.the.money.configure.base.IConfig;
import show.me.the.money.service.dao.DBService;
import show.me.the.money.util.context.Context;


public class Configuration extends DBService {
	private final static Log logger = LogFactory.getLog(Configuration.class);

	@SuppressWarnings("unchecked")
	public void execute(HashMap<String,Object> req, HashMap<String,Object> res, Context ctx){

		String className = (String)req.get("className");	
		String operate = (String)req.get("operate");
		if(StringUtils.isEmpty(className)){
			logger.error("className missing.");
			return;
		}
		if(StringUtils.isEmpty(operate)){
			logger.error("operate missing.");
			return;
		}
		String cls = "ctd.configure." + className;
		
		Object obj = req.containsKey("body")?req.get("body"):req.get("pkey");
		if(obj == null && req.containsKey("cnd")){
			obj = req.get("cnd");
		}		
		
		Object[] param = new Object[1];
		Class[] paramType = new Class[1];
		if(obj == null){
			param = null;
			paramType = null;
		}else{
			param[0] = obj;	
			paramType[0] = obj.getClass();
		}
		
		if(operate.equals("save")){
			String op = (String)req.get("op");
			if(op.equals("update"))
				operate = op;
		}
		try {
			Class ic = Class.forName(cls);
			IConfig iconfig = (IConfig)ic.newInstance();
			iconfig.setCtx(ctx);
			Method method = ic.getMethod(operate, paramType);
			HashMap<String,Object> rec = (HashMap<String,Object>)method.invoke(iconfig, param);
			if(rec != null){
				res.putAll(rec);
			}			
		} catch (Exception e) {
			logger.error(cls+"."+operate+" error",e);
			if(res != null){
				res.put(Service.RES_CODE, 500);
				res.put(Service.RES_MESSAGE, "error");
				logger.error("code:"+res.get(Service.RES_CODE)+"  msg:"+res.get(Service.RES_MESSAGE));
			}				
		}		
	}
}
